const User = require("../models/User");
const Record = require("../models/Record");
const { appid, secret } = require("../config/weappConfig");
const validate = require("validate.js");
const moment = require("moment");
const { Op } = require("sequelize");


const { pick } = require("../util/propertyHelper");

exports.add = async function (recordObj) {
  recordObj = pick(recordObj, ["date", "category", "title", "content", "mood", "images", "UserId"]);

  validate.validators.userExits = async function (value) {
    const c = await User.findByPk(value);
    if (c) {
      return;
    }
    return "is not exist";
  };

  validate.validators.type.types.stringArray = function (value) {
    if (Array.isArray(value)) {
      for (let i = 0; i < value.length; i++) {
        if (typeof value[i] !== "string" || !value[i]) {
          return false;
        }
      };
      return true;
    }
    return false;
  }


  const rule = {
    title: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
      length: { minimum: 1, maximum: 20 },
    },
    content: {
      type: "string",
      presence: {
        allowEmpty: false,
      },
      length: { minimum: 1, maximum: 200 },
    },
    mood: {
      type: "string",
      presence: {
        allowEmpty: false,
      },
      inclusion: ['😊', '😎', '😐', '😢', '😖'],
    },
    images: {
      type: "stringArray",

    },
    date: {
      presence: {
        allowEmpty: false,
      },
      datetime: {
        dateOnly: true,
        earliest: +moment.utc().subtract(1, "y"),  // 一年前
        latest: +moment.utc(),  // 当前日期
      },
    },
    category: {
      presence: {
        allowEmpty: false,
      },
      inclusion: ['1', '2'], //1锻炼/2饮食
    },
    UserId: {
      presence: {
        allowEmpty: false,
      },
      numericality: {
        onlyInteger: true,
        strict: false,
      },
      userExits: true,
    }
  };

  await validate.async(recordObj, rule); //验证

  await Record.create(recordObj);
  return;
}

exports.getList = async function (
  userId,
  page = 1,
  limit = 10,
  date = '',
) {
  const where = {};
  where.UserId = userId;
  if (date) {
    const parsedDate = new Date(date);
    where.date = {
      [Op.between]: [
        new Date(parsedDate.setHours(0, 0, 0, 0)), // 日期的开始时间
        new Date(parsedDate.setHours(23, 59, 59, 999)) // 日期的结束时间
      ]
    };
  }
  const records = await Record.findAndCountAll({
    where,
    order: [
      ['date', 'DESC']
    ],
    offset: (page - 1) * limit,
    limit: +limit,
  });
  return {
    total: records.count,
    list: JSON.parse(JSON.stringify(records.rows))
  };
}

exports.update = async function (recordId, recordObj) {
  recordObj = pick(recordObj, ["date", "category", "title", "content", "mood", "images", "UserId"]);

  validate.validators.userExits = async function (value) {
    const c = await User.findByPk(value);
    if (c) {
      return;
    }
    return "is not exist";
  }

  validate.validators.type.types.stringArray = function (value) {
    if (Array.isArray(value)) {
      for (let i = 0; i < value.length; i++) {
        if (typeof value[i] !== "string") {
          return false;
        }
      };
      return true;
    }
    return false;
  }

  const rule = {
    title: {
      type: "string",
      length: { minimum: 1, maximum: 20 },
    },
    content: {
      type: "string",
      length: { minimum: 1, maximum: 200 },
    },
    mood: {
      type: "string",
      inclusion: ['😊', '😎', '😐', '😢', '😖'],
    },
    images: {
      type: "stringArray",
    },
    date: {
      datetime: {
        dateOnly: true,
        earliest: +moment.utc().subtract(1, "y"),  // 一年前
        latest: +moment.utc(),  // 当前日期
      },
    },
    category: {
      inclusion: ['1', '2'], //1锻炼/2饮食
    },
  };

  await validate.async(recordObj, rule); //验证

  const record = await Record.findByPk(recordId);
  if (!record) {
    throw new Error('Record not found');
  };

  if (record.UserId !== recordObj.UserId) {
    throw new Error('You can only update your own records');
  };
  await record.update(recordObj);
  return;
}

exports.delete = async function (UserId, recordId) {

  validate.validators.userExits = async function (value) {
    const c = await User.findByPk(value);
    if (c) {
      return;
    }
    return "is not exist";
  };

  const rule = {
    UserId: {
      presence: {
        allowEmpty: false,
      },
      numericality: {
        onlyInteger: true,
        strict: false,
      },
      userExits: true,
    },
    recordId: {
      presence: {
        allowEmpty: false,
      },
      numericality: {
        onlyInteger: true,
        strict: false,
      },
    }
  }

  await validate.async({ UserId, recordId }, rule);

  const record = await Record.findByPk(recordId);
  if (!record) {
    throw new Error('Record not found');
  };

  if (record.UserId !== UserId) {
    throw new Error('You can only delete your own records');
  };
  await record.destroy();
  return;
}